#include "header.h"
#include "LibManager.h"
#include "FontLib.h"
#include "ConfigFile.h"
#include "Config.h"
#include "Config.h"

#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>

using namespace std;

const ushort LibManager::s_chUnicBegin = 0x4E00;
const ushort LibManager::s_chUnicEnd = 0x9FA5;

void LibManager::appendChars(const char *appendFilePath) {
    Config &config = Config::getInstance();

    const ushort chUnicodeSize = s_chUnicEnd - s_chUnicBegin + 1;
    bitset<chUnicodeSize> maxbs;
    bitset<chUnicodeSize> currbs;

    wstring str;
    vector<ushort> exist, notValid;
    int size;

    // maxLib
    string maxPath = config.getString("path.dir.data") + "/max/library";
    wifstream wfin(maxPath.c_str());
    wfin.imbue(locale(Config::getInstance().getLocale()));

    wfin >> str;

    size = str.size();
    for (int i = 0; i < size; i++) {
        maxbs.set(str[i] - s_chUnicBegin);
    }

    wfin.close();

    // currLib
    str.clear();

    string currPath = config.getString("path.dir.data") + "/curr/library";
    wfin.open(currPath.c_str());
    if (wfin) {
        wfin >> str;

        size = str.size();
        for (int i = 0; i < size; i++) {
            currbs.set(str[i] - s_chUnicBegin);
        }
        wfin.close();
    }

    // append
    wfin.open(appendFilePath);
    wfin >> str;

    size = str.size();
    for (int i = 0; i < size; i++) {
        if (str[i] < s_chUnicBegin || str[i] > s_chUnicEnd || maxbs.test(str[i] - s_chUnicBegin) == false) {
            notValid.push_back(str[i]);
            continue;
        }

        if (currbs.test(str[i] - s_chUnicBegin)) {
            exist.push_back(str[i]);
            continue;
        }

        currbs.set(str[i] - s_chUnicBegin);
    }
    wfin.close();

    size = exist.size();
    if (size > 0) {
        wcout << "exist=";
        for (int i = 0; i < size; i++) {
            wcout << (wchar_t)exist[i];
        }
        wcout << endl;
    }

    size = notValid.size();
    if (size > 0) {
        wcout << "not valid=";
        for (int i = 0; i < size; i++) {
            wcout << (wchar_t)notValid[i];
        }
        wcout << endl;
    }

    wofstream wfout(currPath.c_str());
    for (ushort i = 0; i < chUnicodeSize; i++) {
        if (currbs.test(i)) {
            wfout << (wchar_t)(s_chUnicBegin + i);
        }
    }
    wfout.close();

    FontLib::genCurrFontLib();
}
